<?php

namespace app\controllers;

use app\models\Fbx;
use app\models\Image;
use app\models\UploadForm;
use app\models\File;
use app\models\Data;
use Yii;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;

/**
 * Created by PhpStorm.
 * User: blacxhunt
 * Date: 2017/06/23
 * Time: 11:38
 */
class FileController extends \yii\web\Controller
{
    public function actionSubmit(){
        $data = Yii::$app->request->post();
        $model = new File();
        $model->url = $data["fbx"]["url"];
        $model->md5 = $data["fbx"]["md5"];
        $model->type = $data["fbx"]["type"];
        $model->title = $data["fbx"]["title"];
        $model->user_id = Yii::$app->user->id;

        
        $image = new File();
        $image->url = $data["image"]["url"];
        $image->md5 = $data["image"]["md5"];
        $image->type = $data["image"]["type"];
        $image->title = $data["image"]["title"];
        $image->user_id = Yii::$app->user->id;

        if($model->save() && $image->save()){
            $data = new Data();
            $data->model_id = $model->id;
            $data->image_id = $image->id;
            $data->user_id = Yii::$app->user->id;
            $data->created_at = date('Y-m-d H:i:s');

            if($data->save()){
            
                return json_encode($data->id);
            }else{
                 return "no";
            }


        }

        return json_encode($model->user_id);
    }
    public function actionUpload(){
        $data = Yii::$app->request->post();
        $file = UploadedFile::getInstanceByName('file');
        $path = 'files/upload/'."_".$data['md5'];
        if($data['skip'] == 0){
           $file->saveAs($path);
        }else{
            file_put_contents($path, file_get_contents($file->tempName), FILE_APPEND);
        }

        if($data['size'] <= $data['upload_size'] ){
            $md5 = md5_file($path);
            if( $md5 == $data['md5']){
                rename($path, 'files/upload/'.$data['md5']);
                return "cool";
            }
        }
        echo json_encode($data);

    }
}
